package com.example.ignite.config;

import com.example.ignite.service.Cache;
import com.example.ignite.service.IgniteCacheImpl;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCluster;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.CacheWriteSynchronizationMode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class IgniteConfig {
    @Bean
    Ignite ignite() {
        IgniteConfiguration cfg = new IgniteConfiguration();
        cfg.setClientMode(true);
        cfg.setPeerClassLoadingEnabled(true);

        CacheConfiguration cacheConfiguration = new CacheConfiguration();
        cacheConfiguration.setName("item");
        cacheConfiguration.setCacheMode(CacheMode.PARTITIONED);
        cacheConfiguration.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
        cacheConfiguration.setBackups(2);
        cacheConfiguration.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);


        cfg.setCacheConfiguration(cacheConfiguration);
        Ignite ignite = Ignition.start(cfg);
        return ignite;
    }

    @Bean
    Cache<Integer, String> itemCache(Ignite ignite) {
        ignite.destroyCache("item");
        IgniteCache<Integer, String> cache =  ignite.getOrCreateCache("item");
        return new IgniteCacheImpl<Integer, String>(ignite, cache);
    }
}
